package test.panel4;

import test.panel3.ProcessTableInPanel;

import javax.swing.*;
import java.awt.*;

public class ProcessPanel extends JPanel {
    Process process;

    JLabel nameLable;

    public ProcessPanel(Process process) {
        this.process = process;
        this.setLayout(new FlowLayout(FlowLayout.LEFT));
        this.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        Dimension fixedHeight = new Dimension(Panel4.getInstance().right_Panel.getSize().width - 15, 50);
        this.setPreferredSize(fixedHeight);
        this.setMaximumSize(fixedHeight);
        //显示pid和name
        JLabel pid = new JLabel("pid:" + process.pid);
        nameLable = new JLabel(process.name);
        this.add(pid);
        this.add(nameLable);
        //创建挂起/激活按钮
        if (process.isRunning) {
            JButton suspendButton = new JButton("挂起");
            suspendButton.addActionListener(e -> {
                Control.suspend(process);
            });
            this.add(suspendButton);
        } else {
            JButton activateButton = new JButton("激活");
            activateButton.addActionListener(e -> {
                Control.active(process);
            });
            this.add(activateButton);
        }
        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(e -> {
            ProcessTableInPanel.getInstance().deleteData(process);
            //释放资源
            if (process.resourceFlag) {
                process.resourceFlag = false;
                ResourceGUI.getInstance().releaseResources(process);
            }
            Control.delete(process);
        });
        this.add(deleteButton);
        //创建详细设计按钮
        if (!process.isRunning) {
            JButton settingButton = new JButton("详细设置");
            settingButton.addActionListener(e -> {
                Control.setting(process);
            });
            this.add(settingButton);
        }
        //创建显示按钮
        JButton displayButton = new JButton("显示进程信息");
        displayButton.addActionListener(e -> {
            System.out.println(process.toString()
                    .concat("\n所需资源：")
                    .concat(process.Needs.toString()));
        });
        this.add(displayButton);
    }

    public void setName(String name) {
        nameLable.setText(name);
    }
}
